import { Op } from 'sequelize'
import { IfindParmas } from '../../until/Interface'
import { DataModel, StatusModel, DateRecord } from '../../until/context'
import Tool from '../../until/tool'
import { logger } from '../../until/log'

class DataService { 
       public static async myFindAll(options: IfindParmas) {
        let {startPosition,limit,where,attributes,model}:{startPosition: number, limit: number, where: Object,attributes: Array<string>,model:any}  = options
        if (options.multi) {
            let {rows,count} = await model.findAndCountAll({
                attributes,
                where: {
                    [Op.and]: {
                        ...where
                    }
                },
                offset: startPosition,
                limit
            })
            return {total: count, data: rows}
        } else {
            let res = await model.findAndCountAll({
                attributes,
                where: {
                    ...where
                },
                offset: startPosition,
                limit,
                order: [
                    ['createdAt', 'DESC']
                ]
            })
            return {total: res.count, data:res.rows}
        }

    }
    // 获取数据列表
    async getDataList(pageSize,page,query) {
        let startPosition:number = (page - 1)*pageSize  // 查询的起始位置
        let total:number = 0
        if (query !=='') {
            let data = await DataModel.findAll({
                attributes: ["uvc","inf","tem","hum","pre","createdAt","module_id","gateway_ip"],
                where: {
                    date: query
                },
                offset: startPosition,
                limit: pageSize
            })
            total = await DataModel.count({
                where: {
                    date: query
                }
            })
            return {data,total}
        } else {
            try {
                let data = await DataModel.findAll({
                    attributes: ["uvc","inf","tem","hum","pre","createdAt","module_id","gateway_ip"],
                    offset: startPosition,
                    limit: pageSize
                })
                total = await DataModel.count()
                return {data,total}
            } catch(err) {
                console.log(err)
            }

        }
    }
    async getStatusDataList(pageSize,page,queryDate,queryType) {
        let startPosition:number = (page - 1) * pageSize  // 查询的起始位置
        let total:number = 0
        if (queryDate !=='' && queryType !== '') {
            let data = await StatusModel.findAll({
                attributes: ["uvc_sta","ir_sta","temp_sta","hum_sta","pre_sta","createdAt","module_id","gateway_ip"],
                where: {
                    [Op.and]: {
                        date: queryDate,
                        [Op.or]: {
                            uvc_sta: queryType,
                            ir_sta: queryType,
                            temp_sta: queryType,
                            hum_sta: queryType,
                            pre_sta: queryType
                        }
                    }
                },
                offset: startPosition,
                limit: pageSize
            })
            total = await StatusModel.count({
                where: {
                    [Op.and]: {
                        date: queryDate,
                        [Op.or]: {
                            uvc_sta: queryType,
                            ir_sta: queryType,
                            temp_sta: queryType,
                            hum_sta: queryType,
                            pre_sta: queryType
                        }
                    }
                }
            })
            return {data,total}
        } else if(queryDate === '' && queryType !== '') {
            let data = await StatusModel.findAll({
                attributes: ["uvc_sta","ir_sta","temp_sta","hum_sta","pre_sta","createdAt","module_id","gateway_ip"],
                where: {
                    [Op.or]: [
                        { uvc_sta: queryType},
                        { ir_sta: queryType},
                        {hum_sta: queryType},
                        {temp_sta: queryType},
                        {pre_sta: queryType}
                    ]
                },
                offset: startPosition,
                limit: pageSize
            })
            total = await StatusModel.count({
                where: {
                    [Op.or]: [
                        { uvc_sta: queryType},
                        { ir_sta: queryType},
                        {hum_sta: queryType},
                        {temp_sta: queryType},
                        {pre_sta: queryType}
                    ]
                }
            })
            return {data,total}
        } else if (queryDate !== '' && queryType == '') {
            let data = await StatusModel.findAll({
                attributes: ["uvc_sta","ir_sta","temp_sta","hum_sta","pre_sta","createdAt","module_id","gateway_ip"],
                where: {
                    date: queryDate
                },
                offset: startPosition,
                limit: pageSize
            })
            total = await StatusModel.count({
                where: {
                    date: queryDate
                }
            })
            return {data,total}
        } else {
            let data = await StatusModel.findAll({
                attributes: ["uvc_sta","ir_sta","temp_sta","hum_sta","pre_sta","createdAt","module_id","gateway_ip"],
                offset: startPosition,
                limit: pageSize
            })
            total = await StatusModel.count()
            return {data,total}
        }
    }
    // 获取可以下载的日期
    async downLoadDate() {
        return await DateRecord.findAll({
            attributes: ["rid","currentDate"],
            group: ["currentDate"]
        })
    }

    // 下载运行时的数据并且导入成为excel
    async downloadRunData(date) {
        let data = await DataModel.findAll({
            attributes: ["uvc","inf","tem","hum","pre","date","time","module_id","gateway_ip"],
            where: {
                date
            }
        })
        return data
    }

    async getItem(date) {
        return await DataModel.count({
            where: {
                date
            }
        })
    }
       //数据保存
       async saveDataList(data) {
        await DataModel.create({
            ...data,
            time: new Date().toLocaleTimeString(),
            date: Tool.getCurrentDate()
        })
     }

     // 批量数据保存
     async batchSaveDataList(dataList: any[]) {
        if (dataList.length === 0) {
            return;
        }
        const recordsToCreate = dataList.map(data => ({
            ...data,
            date: Tool.getCurrentDate()
        }));
        await DataModel.bulkCreate(recordsToCreate);
        console.log(`批量存储 ${recordsToCreate.length} 条数据成功。`);
    }

     //数据状态保存
     async saveStatusList(data) {
        await StatusModel.create({
            ...data,
            time: new Date().toLocaleTimeString(),
            date: Tool.getCurrentDate()
        })
     }
     async addRunDate() {
  
        const dateList: string[] = (await this.downLoadDate()).map(item => item.currentDate)
        const currentDate:string = Tool.getCurrentDate()
        if (dateList.includes(currentDate)) return logger.info("该日期已经存在了")
        // 创建运行日期数据
        await DateRecord.create({
            currentDate: Tool.getCurrentDate()
        })
        console.log("运行日期数据保存成功" + currentDate)
        logger.info("运行日期数据保存成功" + currentDate)
        const isDel: boolean = await this.isDel()
        if (isDel) {
            console.log("数据超过了七天需要定时删除数据")
            await this.deleteData()
        }
     }

    async isDel() {
        let res = await DateRecord.count()
        return res > 7
    }
    async deleteData() {
        let result = await DateRecord.findAll({
            limit: 7,
            order: [
                ["createdAt","desc"]
            ]
        })
        let dateList = result.map(item => item.currentDate)

        // 删除日期数据
        await DateRecord.destroy({
            where: {
                currentDate: {
                    [Op.not]: dateList
                }
            }
        })
        // 删除状态数据
        await StatusModel.destroy({
            where: {
                date: {
                    [Op.not]: dateList
                }
            }
        })

        // 删除运行数据
        await DataModel.destroy({
            where: {
                date: {
                    [Op.not]: [dateList]
                }
            }
        })
    }
        // 批量存储数据
    async batchSaveData(data: any) {
        let uvList: number[] = data.data[0]
        let dataList: Array<Record<string, any>> = []
        for (let i = 0; i < uvList.length; i++) {
            dataList.push({
                uvc: uvList[i],
                inf: data.data[1],
                tem: data.data[2],
                hum: data.data[3],
                pre: data.data[4],
                module_id: data.ID,
                time: new Date().toLocaleTimeString(),
                date: Tool.getCurrentDate()
            })
        }   
        let res = await DataModel.bulkCreate(dataList)
        return res
    }

    // 获取初始化数据值
    async getInitialData(gateway_ip: string, module_id: string) {
        try {
            // 获取温度、湿度、压力、红外的最近10条数据
            const normalData = await DataModel.findAll({
                attributes: ["time","uvc", "inf", "tem", "hum", "pre", "createdAt", "module_id", "gateway_ip"],
                where: {
                    gateway_ip,
                    module_id
                },
                order: [
                    ['createdAt', 'DESC']
                ],
                limit: 10
            });

            // 获取紫外线的最近一条数据（如果紫外线数据是一次性10个点的话）
            const uvData = await DataModel.findOne({
                attributes: ["uvc"],
                where: {
                    gateway_ip,
                    module_id
                },
                order: [
                    ['createdAt', 'DESC']
                ]
            });

            return {
                normalData: normalData.reverse(),
                uvData
            };
        } catch (error) {
            logger.error(`获取初始化数据失败: ${error}`);
            throw error;
        }
    }
}

export default new DataService();